package com.lw.leetcode.sort.b;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 1797. 设计一个验证系统
 *
 * @author liw
 * @version 1.0
 * @date 2023/2/9 9:26
 */
public class AuthenticationManager {

    private int timeToLive;
    private TreeMap<Integer, Node> map;
    private Map<String, Node> idMap;
    private int count;
    private List<String> list = new ArrayList<>();

    public AuthenticationManager(int timeToLive) {
        this.timeToLive = timeToLive;
        this.map = new TreeMap<>();
        this.idMap = new HashMap<>();
    }

    public void generate(String tokenId, int currentTime) {
        int end = currentTime + timeToLive;
        Node item = new Node(tokenId, end);
        map.put(end, item);
        idMap.put(tokenId, item);
        count++;
    }

    public void renew(String tokenId, int currentTime) {
        Node node = idMap.get(tokenId);
        if (node == null) {
            return;
        }
        map.remove(node.end);
        if (node.end <= currentTime) {
            idMap.remove(tokenId);
            count--;
            return;
        }
        node.end = currentTime + timeToLive;
        map.put(node.end, node);
    }

    public int countUnexpiredTokens(int currentTime) {
        list.clear();
        for (Map.Entry<Integer, Node> entry : map.entrySet()) {
            if (entry.getValue().end <= currentTime) {
                list.add(entry.getValue().id);
            } else {
                break;
            }
        }
        count -= list.size();
        for (String s : list) {
            map.remove(idMap.get(s).end);
            idMap.remove(s);
        }
        return count;
    }

    private class Node {
        private String id;
        private int end;

        public Node(String id, int end) {
            this.id = id;
            this.end = end;
        }
    }

}
